import Foundation
import SwiftUI

public struct ColorModel: RawRepresentable {
    public var light: Color
    public var dark: Color

    public var rawValue: String {
        let lh = light.hexString
        let dh = dark.hexString
        return "{\"light\": \"\(lh)\", \"dark\": \"\(dh)\"}"
    }
    
    public init(light: Color, dark: Color) {
        self.light = light
        self.dark = dark
    }
    
    public init?(rawValue: String) {
        guard let data = rawValue.data(using: .utf8),
              let obj = try? JSONSerialization.jsonObject(with: data) as? [String: String],
              let lightStr = obj["light"],
              let darkStr = obj["dark"] else {
            self.light = .Light.accent
            self.dark = .Dark.accent
            return
        }
        self.light = Color(hex: lightStr)
        self.dark = Color(hex: darkStr)
    }
    
    public var color: Color {
        switch Preference.shared.theme {
        case .system: isDarkMode ? dark : light
        case .light: light
        case .dark: dark
        }
    }

    public func color(_ scheme: ColorScheme) -> Color {
        switch Preference.shared.theme {
        case .system:
            if scheme == .dark {
                dark
            } else {
                light
            }
        case .light: light
        case .dark: dark
        }
    }
}

public extension ColorModel {
    static let accent = ColorModel(light: .Light.accent, dark: .Dark.accent)   // 主色调

    static let background: ColorModel = ColorModel(light: .Light.background, dark: .Dark.background)   // 背景

    static let normal: ColorModel = ColorModel(light: .Light.normal, dark: .Dark.normal)   // 一般日期

    static let week: ColorModel = ColorModel(light: .Light.week, dark: .Dark.week)    // 周末

    static let festival: ColorModel = ColorModel(light: .Light.festival, dark: .Dark.festival)    // 节日

    static let current: ColorModel = ColorModel(light: .Light.current, dark: .Dark.current)    // 当前

    static let calendar: ColorModel = ColorModel(light: .Light.calendar, dark: .Dark.calendar)   // 日历事件

    static let reminder: ColorModel = ColorModel(light: .Light.reminder, dark: .Dark.reminder)    // 提醒事件

    static let work: ColorModel = ColorModel(light: .Light.work, dark: .Dark.work)    // 加班

    static let rest: ColorModel = ColorModel(light: .Light.rest, dark: .Dark.rest)    // 休息

    static let taboo: ColorModel = ColorModel(light: .Light.taboo, dark: .Dark.taboo)   //  宜

    static let avoid: ColorModel = ColorModel(light: .Light.avoid, dark: .Dark.avoid)   // 忌
}
